import express from 'express'
import path from 'path'
import { loadPlugins } from './pluginLoader.js'
import { __dirname } from '../../../components/Path.js'
import Config from '../../../model/base/Config.js'
export const port = Config.GetCfg('api').port || 80

export const createServer = (logger) => {
  const app = express()

  // 请求日志
  app.use((req, res, next) => {
    const { method, headers } = req
    const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.socket.remoteAddress
    const route = req.originalUrl || req.url
    logger.server('debug', `[请求] IP: ${ip} 方法: ${method} 路由: ${route} 请求头: ${JSON.stringify(headers)} 响应时间: ${Date.now() - req.startTime}ms`)
    res.on('finish', () => {
      logger.server('info', `[响应] IP: ${ip} 状态码: ${res.statusCode} 路由: ${route} 响应时间: ${Date.now() - req.startTime}ms`)
    })
    req.startTime = Date.now()
    next()
  })

  app.use(express.json())

  // 插件加载
  logger.server('info', '开始加载插件...')
  try {
    loadPlugins(app, path.join(__dirname, 'plugins'), logger)
    logger.server('info', '插件加载成功')
  } catch (pluginError) {
    logger.server('error', `插件加载失败: ${pluginError.message}`)
  }

  // 原神,启动!
  const listener = app.listen(port, () => {
    logger.server('info', `服务器成功启动，监听端口 ${port}`)
  })

  // 错误处理
  listener.on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      logger.server('error', `端口 ${port} 被占用，请检查是否有其他服务在运行`)
    } else {
      logger.server('error', `服务器启动失败: ${err.message}`)
    }
  })

  return { app, listener }
}
